package com.jeeplus.modules.guide.utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.config.properties.JeePlusProperites;
import com.jeeplus.modules.guide.entity.*;
import com.jeeplus.modules.guide.service.MobileItemService;
import com.jeeplus.modules.guide.service.MobileMatterService;
import com.jeeplus.modules.guide.web.MobileIndexController;
import com.jeeplus.modules.sys.entity.MobileUserQR;
import com.jeeplus.modules.sys.utils.UserUtils;
import okhttp3.*;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import sun.misc.BASE64Decoder;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.jeeplus.modules.work.queue.utils.HttpUtilsBDC.SendPost;

@Component
public class MatterUtils {
    private static final Logger log = LoggerFactory.getLogger(MobileIndexController.class);
    public static final String SUCCESSCODE = "200";
    @Autowired
    MobileMatterService mobileMatterService;
    @Autowired
    MobileItemService mobileItemService;
    //第三方token
    @Value("${tokenUrl}")
    private String tokenUrl;
    //第三方token
    @Value("${tokenThing}")
    private String tokenThing;
    //获取第三方登录token
    //第三方事项接口
    @Value("${matterUrl}")
    private String matterUrl;
    //第三方情形化接口
    @Value("${sisutionUrl}")
    private String sisutionUrl;
    //第三方情形化材料接口
    @Value("${materialUrl}")
    private String materialUrl;
    //第三方事项地址接口
    @Value("${MatterAddressUrl}")
    private String MatterAddressUrl;
    //第三方一件事接口
    @Value("${OneThingUrl}")
    private String OneThingUrl;
    //第三方情形化操作接口
    @Value("${sisutionDoUrl}")
    private String sisutionDoUrl;
    //第三方一件事详细接口
    @Value("${ThingValueUrl}")
    private String ThingValueUrl;
    //第三方一件事情形接口
    @Value("${ThingSisutionUrl}")
    private String ThingSisutionUrl;
    //第三方一件事情形材料接口
    @Value("${ThingSisutionMatterUtilsUrl}")
    private String ThingSisutionMatterUtilsUrl;
    //第三方事项材料接口
    @Value("${MatterMaterialUrl}")
    private String MatterMaterialUrl;
    //第三方一页一证材料下载接口
    @Value("${ThingFile}")
    private String ThingFile;
    //第三方一页一证网办办件编码接口
    @Value("${ThingCodeUrl}")
    private String ThingCodeUrl;
    //第三方一页一证网办地址接口
    @Value("${ThingDoUrl}")
    private String ThingDoUrl;
    //移动端下载前缀
    @Value("${uploadUrl}")
    private String uploadUrl;
    //获取一页一证办件数据
    @Value("${ThingHandlingUrl}")
    private String ThingHandlingUrl;

    //芳草街道未办结集合地址
    @Value("${fczwUnFinshedUrl}")
    private String fczwUnFinshedUrl;
    //芳草街道办结集合地址
    @Value("${fczwFinshedUrl}")
    private String fczwFinshedUrl;

    //肖家河街道未办结集合地址
    @Value("${xjzwUnFinshedUrl}")
    private String xjzwUnFinshedUrl;
    //肖家河街道办结集合地址
    @Value("${xjzwFinshedUrl}")
    private String xjzwFinshedUrl;

    //单事项网上办链接
    @Value("${MatterDoUrl}")
    private String MatterDoUrl;

    //获取单事项网上办编码链接
    @Value("${MatterCodeUrl}")
    private String MatterCodeUrl;


    /**
     * 不动产登录账号
     */
    @Value("${realEstateLoginName}")
    private String realEstateLoginName;
    /**
     * 不动产登录密码
     */
    @Value("${realEstatePassWord}")
    private String realEstatePassWord;
    /**
     * 不动产机构标识
     */
    @Value("${realEstateIdentification}")
    private String realEstateIdentification;
    /**
     * 不动产密钥
     */
    @Value("${realEstateSecretKey}")
    private String realEstateSecretKey;

    /**
     * 不动产系统排号信息上传参考号使用前需要先在前面拼接日期（格式：20220111）
     */
    @Value("${realEstateInfoRefId}")
    private String realEstateInfoRefId;

    /**
     * 不动产系统Token参考号使用前需要先在前面拼接日期（格式：20220111）
     */
    @Value("${realEstateTokenRefId}")
    private String realEstateTokenRefId;


    /**
     * 不动产Token报文编号
     */
    @Value("${realEstateTokenTrnCode}")
    private String realEstateTokenTrnCode;
    /**
     * 不动产获取办件信息报文编号
     */
    @Value("${realEstateDoThingInfoTrnCode}")
    private String realEstateDoThingInfoTrnCode;
    /**
     * 行政审批局token
     */
    @Value("${xzspj_token}")
    private String xzspj_token;

    /**
     * 行政审批局街道列表
     */
    @Value("${xzspj_streetList}")
    private String xzspj_streetList;

    /**
     * 行政审批局是否一代多
     */
    @Value("${xzspj_companyCode}")
    private String xzspj_companyCode;
    /**
     * 行政审批局账号
     */
    @Value("${xzspj_username}")
    private String xzspj_username;
    /**
     * 行政审批局密码
     */
    @Value("${xzspj_pwd}")
    private String xzspj_pwd;

    /**
     * 芳草作废接口
     */
    @Value("${fczwdelUrl}")
    private String fczwdelUrl;

    /**
     * 肖家河作废接口
     */
    @Value("${xjzwdelUrl}")
    private String xjzwdelUrl;

    //获取事项
    public void getMatterValue(String version) {
        int pageNumber = 1, pageSize = 1;
        int count = 0;
        JSONObject jsonObject;
        jsonObject = JSONObject.parseObject(HttpRequestUtil.sendPostByToken(matterUrl + "?pageNumber=" + pageNumber + "&pageSize=" + pageSize, tokenThing));
        List<MobileMatter> list;
        if (null != jsonObject) {
            count = jsonObject.getInteger("count");
            if (count >= 1) {
                pageSize = 10;
                count = (count - 1) / pageSize + 1;
                for (int i = 1; i <= count; i++) {
                    try {
                        jsonObject = JSONObject.parseObject(HttpRequestUtil.sendPostByToken(matterUrl + "?pageNumber=" + i + "&pageSize=" + pageSize, tokenThing));
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error(e.getMessage());
                    }
                    list = JSONArray.parseArray(jsonObject.getString("data"), MobileMatter.class);
                    try {
                        for (MobileMatter m : list) {
                            if (null != m.getMaterialList() && m.getMaterialList().length >= 1) {
                                m.setMaterialListValue(JSONArray.toJSON(m.getMaterialList()).toString());
                            }else{
                                m.setMaterialListValue("[]");
                            }
                            if (null != m.getLocationAddr() && m.getLocationAddr().size() >= 1) {
                                m.setLocationAddrValue(JSONArray.toJSON(m.getLocationAddr()).toString());
                            }else{
                                m.setLocationAddrValue("[]");
                            }
                        }
                        mobileMatterService.insertMatterList(version, list);
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error(e.getMessage());
                    }
                    list.clear();
                }
            }
        }
    }

    //获取事项结果查询
    public AjaxJson getInsertMatterValue(String version) {
        if (null == version) return AjaxJson.error("version is null");
        int pageNumber = 1, pageSize = 1;
        int count = 0;
        JSONObject jsonObject = JSONObject.parseObject(HttpRequestUtil.sendPostByToken(matterUrl + "?pageNumber=" + pageNumber + "&pageSize=" + pageSize, tokenThing));
        count = jsonObject.getInteger("count");
        int num = mobileMatterService.findMatterValueCount(version);
        return AjaxJson.success("事项接口条数：" + count + "条\n" + "数据库查询条数：" + num + "条\n" + "version:" + version);
    }


    //所有事项的办理方式及办理信息
    public void getMatterAddress(String version) {
        int pageNumber = 1, pageSize = 1;
        int count = 0;
        JSONObject jsonObject;
        jsonObject = JSONObject.parseObject(HttpRequestUtil.sendPostByToken(MatterAddressUrl + "?pageNumber=" + pageNumber + "&pageSize=" + pageSize, tokenThing));
        List<MobileMatterAddress> list = new ArrayList<>();
        List<MobileMatterAddress> serviceList = new ArrayList<>();
        List<MobileMatterAddress> areaList = new ArrayList<>();
        if (null != jsonObject) {
            count = jsonObject.getInteger("count");
            if (count >= 1) {
                pageSize = 30;
                count = (count - 1) / pageSize + 1;
                for (int i = 1; i <= count; i++) {
                    JSONArray jsonMatter = new JSONArray();
                    try {
                        jsonObject = JSONObject.parseObject(HttpRequestUtil.sendPostByToken(MatterAddressUrl + "?pageNumber=" + i + "&pageSize=" + pageSize, tokenThing));
                        jsonMatter = jsonObject.getJSONArray("data");
                    } catch (Exception e) {
                        log.error(e.getMessage());
                        e.printStackTrace();
                    }
                    try {
                        for (int key = 0; key < jsonMatter.size(); key++) {
                            jsonObject = jsonMatter.getJSONObject(key);
                            if (StringUtils.isNotBlank(jsonObject.getString("serviceList"))) {
                                serviceList = JSONArray.parseArray(jsonObject.getString("serviceList"), MobileMatterAddress.class);
                            }
                            if (StringUtils.isNotBlank(jsonObject.getString("areaList"))) {
                                areaList = JSONArray.parseArray(jsonObject.getString("areaList"), MobileMatterAddress.class);
                            }
                            for (MobileMatterAddress ma : serviceList) {
                                ma.setDoType(1);
                                ma.setOid(jsonObject.getString("oid"));
                                list.add(ma);
                            }
                            serviceList.clear();
                            for (MobileMatterAddress ma : areaList) {
                                ma.setDoType(2);
                                ma.setOid(jsonObject.getString("oid"));
                                list.add(ma);
                            }
                            areaList.clear();
                        }
                        mobileMatterService.insertMatterAddress(list, version);
                    } catch (Exception e) {
                        log.error(e.getMessage());
                        e.printStackTrace();
                        System.out.println("---------error---------" + i);
                    }
                    list.clear();
                }
            }
        }
    }

    //所有事项的办理方式及办理信息结果查询
    public AjaxJson getInsertMatterAddress(String version) {
        if (null == version) return AjaxJson.error("version is null");
        int pageNumber = 1, pageSize = 1;
        int count = 0;
        JSONObject jsonObject = JSONObject.parseObject(HttpRequestUtil.sendPostByToken(MatterAddressUrl + "?pageNumber=" + pageNumber + "&pageSize=" + pageSize, tokenThing));
        count = jsonObject.getInteger("count");
        int num = mobileMatterService.findMatterAddressCount(version);
        return AjaxJson.success("事项点位接口条数：" + count + "条\n" + "数据库查询条数：" + num + "条\n" + "version:" + version);
    }

    //获取事项情形化
    public JSONObject getSisutionValue(String id) {
        JSONObject json = null;
        try {
            json = JSONObject.parseObject(HttpRequestUtil.sendPostByToken(sisutionUrl + id, tokenThing));
            if (SUCCESSCODE.equals(json.getString("code"))) {
                return json;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        log.error("获取获取事项情形化初始化失败！id:" + id + " result=" + json.toJSONString());
        return null;
    }

    //获取事项情形化选择查询
    public JSONObject findSisutionValue(String id) {
        JSONObject json = null;
        try {
            json = JSONObject.parseObject(HttpRequestUtil.sendPostByToken(sisutionDoUrl + id, tokenThing));
            if (SUCCESSCODE.equals(json.getString("code"))) {
                if(json.getJSONArray("data").size() == 1 && json.getJSONArray("data").getJSONObject(0).getString("titleName").equals("默认")){
                    json.replace("data",new JSONArray());
                }
                return json;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        log.error("获取获取事项情形化新失败！id:" + id + " result=" + json.toJSONString());
        return null;
    }

    //获取事项情形化材料
    public JSONObject getMaterialValue(String ids) {
        JSONObject json = null;
        try {
            json = JSONObject.parseObject(HttpRequestUtil.sendPostByToken(materialUrl + ids, tokenThing));
            if (SUCCESSCODE.equals(json.getString("code"))) {
                return json;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        log.error("获取事项情形化材料失败！ids:" + ids + " result=" + json.toJSONString());
        return null;

    }

    //获取事项情形化材料
    public AjaxJson getMatterFile(String attaOid) {
        JSONObject json = null;
        try {
            json = JSONObject.parseObject(HttpRequestUtil.sendPostByToken(MatterMaterialUrl + attaOid, tokenThing));
            if (SUCCESSCODE.equals(json.getString("code")) && StringUtils.isNotBlank(json.getString("data"))) {
                json = JSONObject.parseObject(json.getString("data"));
                byte[] bytes = new BASE64Decoder().decodeBuffer(json.getString("fileBase64"));
                InputStream in = new ByteArrayInputStream(bytes);
                for (int i = 0; i < bytes.length; ++i) {
                    if (bytes[i] < 0) {
                        bytes[i] += 256;
                    }
                }
                String url = JeePlusProperites.newInstance().getUserfilesBaseDir() + JeePlusProperites.USERFILES_BASE_URL + "bszn/" + attaOid + "/";
                com.jeeplus.common.utils.FileUtils.createDirectory(url);
                url = url + json.getString("originName");
                BufferedOutputStream outputStream = null;
                outputStream = new BufferedOutputStream(new FileOutputStream(new File(url)));
                byte[] buffer = new byte[1024];// 字节数组
                while ((in.read(buffer)) != -1) {
                    outputStream.write(buffer);
                }
                outputStream.flush();
                outputStream.close();
                in.close();
                url = uploadUrl + JeePlusProperites.USERFILES_BASE_URL + "bszn/" + attaOid + "/" + json.getString("originName");
                return AjaxJson.success().put("url", url).put("fileName", json.getString("originName"));
            } else {
                return AjaxJson.error("材料为空！").put("code", 400);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        log.error("获取事项材料失败！attaOid:" + attaOid);
        return AjaxJson.error("获取事项材料失败! result=" + json.toJSONString()).put("code", 400);

    }


    //获取事项一页一证一件事
    public Object getOneThing() {
        JSONObject json = null;
        try {
            json = JSONObject.parseObject(HttpRequestUtil.sendPostByToken(OneThingUrl + "?isOneintLicense=N", tokenThing));
            if (SUCCESSCODE.equals(json.getString("code"))) {
                return json;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        log.error("获取事项一页一证一件事失败! result=" + json.toJSONString());
        return null;

    }

    //加载一页一证进数据库
    public void insertOneThing() {
        JSONObject json = null;
        try {
            json = JSONObject.parseObject(HttpRequestUtil.sendPostByToken(OneThingUrl + "?isOneintLicense=N", tokenThing));
            if (SUCCESSCODE.equals(json.getString("code"))) {
                List<MobileThing> list = JSONArray.parseArray(json.getString("data"), MobileThing.class);
                if (null != list && list.size() >= 1) {
                    mobileMatterService.InsertOneThing(list);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        log.error("添加一页一证一件事失败! result=" + json.toJSONString());

    }


    //获取一页一证详细详细信息
    public List<MobileThingBSZN> getThingValue(String oid) {
        JSONObject json = null;
        List<MobileThingBSZN> list = null;
        try {
            json = JSONObject.parseObject(HttpRequestUtil.sendPostByToken(ThingValueUrl + "?packageOid=" + oid, tokenThing));
            if (SUCCESSCODE.equals(json.getString("code")) && StringUtils.isNotBlank(json.getString("data"))) {
                list = JSONArray.parseArray(json.getString("data"), MobileThingBSZN.class);
                return list;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        log.error("获取一件事详细失败 result=" + json.toJSONString());
        return list;
    }

    //获取一页一证情形化信息
    public Object getThingSisution(String oid) {
        JSONObject json = null;
        try {
            json = JSONObject.parseObject(HttpRequestUtil.sendPostByToken(ThingSisutionUrl + "?packageOid=" + oid, tokenThing));
            if (SUCCESSCODE.equals(json.getString("code"))) {
                return json;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        log.error("获取一件事情形化信息失败 result=" + json.toJSONString());
        return null;
    }

    //获取一页一证情形化材料信息
    public Object getThingSisutionMatterUtils(String oid,String ids,String titleIds) {
        JSONObject json = null;
        try {
            json = JSONObject.parseObject(HttpRequestUtil.getSisutionThing(ThingSisutionMatterUtilsUrl, oid,ids,titleIds, tokenThing));
            if (SUCCESSCODE.equals(json.getString("code"))) {
                return json;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        log.error("获取一件事情形化材料信息失败 result=" + json.toJSONString());
        return null;
    }

    //获取一页一证情形化材料
    public AjaxJson getThingFile(String ids) {
        JSONObject json = null;
        try {
            json = JSONObject.parseObject(HttpRequestUtil.sendPostByToken(ThingFile + ids, tokenThing));
            if (SUCCESSCODE.equals(json.getString("code"))) {
                return AjaxJson.success(json);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        log.error("获取一页一证材料失败！attaOid:" + ids);
        return AjaxJson.error("获取一页一证材料失败! result=" + json.toJSONString());

    }

    //获取一页一证网办地址
    public AjaxJson getThingUrl(String oid, String titleIds, String valIds) {
        JSONObject json = null;
        try {
            json = JSONObject.parseObject(HttpRequestUtil.sendPostByToken(ThingCodeUrl + "?packageOid=" + oid + "&titleOids=" + titleIds + "&valOids=" + valIds, tokenThing));
            if (SUCCESSCODE.equals(json.getString("code"))) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("areaName", "高新一业一证");
                map.put("address", ThingDoUrl + json.getString("data"));
                List<Map<String, String>> list = new ArrayList<Map<String, String>>();
                list.add(map);
                return AjaxJson.success().put("data", list).put("number", json.getString("data"));
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        log.error("获取一页一证网办地址失败！oid:" + oid);
        return AjaxJson.error("获取一页一证网办地址失败! result=" + json.toJSONString()).put("code",400);

    }

    //获取单事项网办地址
    public AjaxJson getMatterUrl(String oid, String titleIds, String valIds) {
        JSONObject json = null;
        try {
            if(StringUtils.isNotBlank(valIds)){
                json = JSONObject.parseObject(HttpRequestUtil.sendPostByToken(MatterCodeUrl + "?serviceOid=" + oid + "&titleOids=" + titleIds + "&valOids=" + valIds, tokenThing));
            }else{
                json = JSONObject.parseObject(HttpRequestUtil.sendPostByToken(MatterCodeUrl + "?serviceOid=" + oid, tokenThing));
            }

            if (SUCCESSCODE.equals(json.getString("success"))) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("areaName", "高新事项平台");
                map.put("address", MatterDoUrl + json.getString("data"));
                List<Map<String, String>> list = new ArrayList<Map<String, String>>();
                list.add(map);
                return AjaxJson.success().put("data", list).put("number", json.getString("data"));
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        log.error("获取单事项网办地址失败！oid:" + oid);
        return AjaxJson.error("获取单事项网办地址失败! result=" + json.toJSONString());

    }


    //获取第三方平台办结集合
    public AjaxJson getFinshed(String loginName, MobileUserQR mq) {
        String thingStatus = "5678";
        JSONObject json = null;
        JSONArray jsonArry = null;
        List<Object> list = new ArrayList<>();
        String result = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            //不动产
            result = getRealEstateInfo(mq.getIdcard());
            if(DataUtils.isNotNull(result)) {
                jsonArry = JSONObject.parseArray(result);
                for(int j=0;j<jsonArry.size();j++){
                    if("已办结".equals(jsonArry.getJSONObject(j).getString("ywzt"))){
                        Map<Object,Object> things = new HashedMap();
                        things.put("startTime",jsonArry.getJSONObject(j).getString("slsj"));
                        things.put("endTime",jsonArry.getJSONObject(j).getString("slsj"));
                        things.put("title","不动产服务");
                        things.put("id",jsonArry.getJSONObject(j).getString("iid"));
                        things.put("status",jsonArry.getJSONObject(j).getString("ywzt"));
                        things.put("code","2");
                        things.put("name","不动产服务");
                        things.put("type","bdc");
                        list.add(things);
                    }
                }
            }
            //其他街道
            List<MobileStreet> ms = mobileMatterService.findStreetValueEnd(mq.getGxid());
            for(MobileStreet m : ms){
                list.add(m);
            }
            //芳草
            result = HttpRequestUtil.toHttpStreet(fczwFinshedUrl + loginName);
            if(DataUtils.isNotNull(result)) {
                json = JSONObject.parseObject(result);
                if (SUCCESSCODE.equals(json.getString("code"))) {
                    jsonArry = json.getJSONArray("data");
                    for(int k=0;k<jsonArry.size();k++){
                        jsonArry.getJSONObject(k).put("name",json.getString("areaName"));
                        jsonArry.getJSONObject(k).put("type","street");
                        list.add(jsonArry.getJSONObject(k));
                    }
                }
            }
            //肖家河
            result = HttpRequestUtil.toHttpStreet(xjzwFinshedUrl + loginName);
            if(DataUtils.isNotNull(result)) {
                json = JSONObject.parseObject(result);
                if (SUCCESSCODE.equals(json.getString("code"))) {
                    jsonArry = json.getJSONArray("data");
                    for(int k=0;k<jsonArry.size();k++){
                        jsonArry.getJSONObject(k).put("name",json.getString("areaName"));
                        jsonArry.getJSONObject(k).put("type","street");
                        list.add(jsonArry.getJSONObject(k));
                    }
                }
            }
            //一业一证
            result = HttpRequestUtil.sendPostByToken(ThingHandlingUrl + mq.getIdcard(), tokenThing);
            if(DataUtils.isNotNull(result)) {
                json = JSONObject.parseObject(result);
                if (SUCCESSCODE.equals(json.getString("code"))) {
                    jsonArry = json.getJSONObject("data").getJSONObject("data").getJSONArray("pacCaseList");
                    for(int i=0;i<jsonArry.size();i++){
                        if(StringUtils.isNotBlank(jsonArry.getJSONObject(i).getString("pacStatusStr")) && thingStatus.contains(jsonArry.getJSONObject(i).getString("pacStatus"))){
                            Map<Object,Object> thing = new HashedMap();
                            thing.put("endTime",sdf.format(jsonArry.getJSONObject(i).getDate("finishTime")));
                            thing.put("startTime",sdf.format(jsonArry.getJSONObject(i).getDate("applyTime")));
                            thing.put("title",jsonArry.getJSONObject(i).getString("packageName"));
                            thing.put("id",jsonArry.getJSONObject(i).getString("pacCaseCode"));
                            thing.put("status",jsonArry.getJSONObject(i).getString("pacStatusStr"));
                            thing.put("code",jsonArry.getJSONObject(i).getString("pacStatus"));
                            thing.put("name","综窗平台");
                            thing.put("type","thing");
                            list.add(thing);
                        }
                    }
                }
            }
            return AjaxJson.success().put("data", list);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return AjaxJson.error("加载错误！");
    }

    //获取第三方平台未办结集合
    public AjaxJson getunFinshed(String loginName, MobileUserQR mq) {
        String thingStatus = "1234";//卓凡第三方公司状态值
        JSONObject json = null;
        JSONArray jsonArry = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Object> list = new ArrayList<>();
        try {
            //不动产
            String result = getRealEstateInfo(mq.getIdcard());
            if(DataUtils.isNotNull(result)) {
                jsonArry = JSONObject.parseArray(result);
                for(int j=0;j<jsonArry.size();j++){
                    if(!"已办结".equals(jsonArry.getJSONObject(j).getString("ywzt"))){
                        Map<Object,Object> things = new HashedMap();
                        things.put("startTime",jsonArry.getJSONObject(j).getString("slsj"));
                        things.put("title","不动产服务");
                        things.put("id",jsonArry.getJSONObject(j).getString("iid"));
                        things.put("status",jsonArry.getJSONObject(j).getString("ywzt"));
                        things.put("code","1");
                        things.put("name","不动产服务");
                        things.put("type","bdc");
                        list.add(things);
                    }
                }
            }

            //其他街道
            List<MobileStreet> ms = mobileMatterService.findStreetValueStart(mq.getGxid());
            for(MobileStreet m : ms){
                list.add(m);
            }
            //芳草
            result = HttpRequestUtil.toHttpStreet(fczwUnFinshedUrl + loginName);
            if(DataUtils.isNotNull(result)) {
                json = JSONObject.parseObject(result);
                if (SUCCESSCODE.equals(json.getString("code"))) {
                    jsonArry = json.getJSONArray("data");
                    for(int k=0;k<jsonArry.size();k++){
                        jsonArry.getJSONObject(k).put("name",json.getString("areaName"));
                        jsonArry.getJSONObject(k).put("type","street");
                        list.add(jsonArry.getJSONObject(k));
                    }
                }
            }
            //肖家河
            result = HttpRequestUtil.toHttpStreet(xjzwUnFinshedUrl + loginName);
            if(DataUtils.isNotNull(result)) {
                json = JSONObject.parseObject(result);
                if (SUCCESSCODE.equals(json.getString("code"))) {
                    jsonArry = json.getJSONArray("data");
                    for(int k=0;k<jsonArry.size();k++){
                        jsonArry.getJSONObject(k).put("name",json.getString("areaName"));
                        jsonArry.getJSONObject(k).put("type","street");
                        list.add(jsonArry.getJSONObject(k));
                    }
                }
            }

            //一业一证
            result = HttpRequestUtil.sendPostByToken(ThingHandlingUrl + mq.getIdcard(), tokenThing);
            if(DataUtils.isNotNull(result)) {
                json = JSONObject.parseObject(result);
                if (SUCCESSCODE.equals(json.getString("code"))) {
                    jsonArry = json.getJSONObject("data").getJSONObject("data").getJSONArray("pacCaseList");
                    for(int i=0;i<jsonArry.size();i++){
                        if(StringUtils.isNotBlank(jsonArry.getJSONObject(i).getString("pacStatusStr")) && thingStatus.contains(jsonArry.getJSONObject(i).getString("pacStatus"))){
                            Map<Object,Object> thing = new HashedMap();
                            thing.put("startTime",sdf.format(jsonArry.getJSONObject(i).getDate("applyTime")));
                            thing.put("title",jsonArry.getJSONObject(i).getString("packageName"));
                            thing.put("id",jsonArry.getJSONObject(i).getString("pacCaseCode"));
                            thing.put("status",jsonArry.getJSONObject(i).getString("pacStatusStr"));
                            thing.put("code",jsonArry.getJSONObject(i).getString("pacStatus"));
                            thing.put("name","一业一证");
                            thing.put("type","thing");
                            list.add(thing);
                        }
                    }
                }
            }
            return AjaxJson.success().put("data", list);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return AjaxJson.error("加载错误！");
    }

    /**
     * 获取Token
     * @return Token
     */
    public String getTokenBDC(){
        long l = System.currentTimeMillis() / 1000;
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式
        String format = df.format(new Date());
        String StringA="{"+
                "\"MsgHeader\":{"+
                "\"TrnCode\":\""+realEstateTokenTrnCode+"\","+
                "\"RefId\":\""+format+realEstateTokenRefId+"\","+
                "\"ReqRefId\":\"\","+
                "\"Token\":\"\","+
                "\"Remark\":\"\""+
                "},"+
                "\"MsgBody\":{"+
                "\"LoginName\":\""+realEstateLoginName+"\","+
                "\"PassWord\":\""+realEstatePassWord+"\""+
                "}}";
        String sign="Content="+StringA+"&Key="+realEstateSecretKey+"&Timestamp="+l;
        sign = DigestUtils.md5DigestAsHex(sign.getBytes()).toUpperCase();
        String parameter="{"+
                "\"Content\":\"{"+
                "\\\"MsgHeader\\\":{"+
                "\\\"TrnCode\\\":\\\""+realEstateTokenTrnCode+"\\\","+
                "\\\"RefId\\\":\\\""+format+realEstateTokenRefId+"\\\","+
                "\\\"ReqRefId\\\":\\\"\\\","+
                "\\\"Token\\\":\\\"\\\","+
                "\\\"Remark\\\":\\\"\\\""+
                "},"+
                "\\\"MsgBody\\\":{"+
                "\\\"LoginName\\\":\\\""+realEstateLoginName+"\\\","+
                "\\\"PassWord\\\":\\\""+realEstatePassWord+"\\\""+
                "}"+
                "}\","+
                "\"OrgId\":\""+realEstateIdentification+"\","+
                "\"Sign\":\""+sign+"\","+
                "\"Timestamp\":\""+l+"\""+
                "}";
        try{
            String s = SendPost(parameter);
            if(null == s || "".equals(s)) return null;
            s = net.sf.json.JSONObject.fromObject(s).getString("Content");
            s = net.sf.json.JSONObject.fromObject(s).getJSONObject("MsgBody").getString("Token");
            return s;
        }catch (Exception e){
        }
        return null;

    }

    public String getRealEstateInfo(String idCard){
        long l = System.currentTimeMillis() / 1000;
        //获取token
        String token=getTokenBDC();if(null == token)return null;
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        String format = df.format(new Date());
        String StringA="{"+
                "\"MsgHeader\":{"+
                "\"TrnCode\":\""+realEstateDoThingInfoTrnCode+"\","+
                "\"RefId\":\""+format+realEstateInfoRefId+"\","+
                "\"ReqRefId\":\"\","+
                "\"Token\":\""+token+"\","+
                "\"Remark\":\"\""+
                "},"+
                "\"MsgBody\":{"+
                "\"zjhm\":\""+idCard+"\""+
                "}" +
                "}";
        net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(StringA);
        String sign="Content="+jsonObject.toString()+"&Key="+realEstateSecretKey+"&Timestamp="+l;
        sign = DigestUtils.md5DigestAsHex(sign.getBytes()).toUpperCase();
        String parameter="{"+
                "\"Content\":\"{"+
                "\\\"MsgHeader\\\":{"+
                "\\\"TrnCode\\\":\\\""+realEstateDoThingInfoTrnCode+"\\\","+
                "\\\"RefId\\\":\\\""+format+realEstateInfoRefId+"\\\","+
                "\\\"ReqRefId\\\":\\\"\\\","+
                "\\\"Token\\\":\\\""+token+"\\\","+
                "\\\"Remark\\\":\\\"\\\""+
                "},"+
                "\\\"MsgBody\\\":{"+
                "\\\"zjhm\\\":\\\""+idCard+"\\\""+
                "}}\","+
                "\"OrgId\":\""+"43"+"\","+
                "\"Sign\":\""+sign+"\","+
                "\"Timestamp\":\""+l+"\""+
                "}";
        String s = SendPost(parameter);
        if(s == null || "".equals(s)) return null;
        try{
            s = net.sf.json.JSONObject.fromObject(s).getString("Content");
            s = net.sf.json.JSONObject.fromObject(s).getJSONObject("MsgBody").getString("DataInfo");
            return s;
        }catch (Exception e){}
        return null;

    }

    public Object streetList(){
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        Request request = new Request.Builder()
                .url(xzspj_streetList)
                .method("GET", null)
                .addHeader("token", this.getTokenXZSPJ())
                .addHeader("username", xzspj_username)
                .build();
        try{
            Response response = client.newCall(request).execute();
            return net.sf.json.JSONObject.fromObject(response.body().string().toString());
        }catch (Exception e){}
        return null;
    }

    public Object getCompanyCode(String code){
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        Request request = new Request.Builder()
                .url(xzspj_companyCode+code)
                .method("GET", null)
                .addHeader("token", getTokenXZSPJ())
                .addHeader("username", xzspj_username)
                .build();
        try{
            Response response = client.newCall(request).execute();
            return net.sf.json.JSONObject.fromObject(response.body().string().toString());
        }catch (Exception e){}
        return null;
    }

    public String getTokenXZSPJ(){
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\r\n\"username\": \""+xzspj_username+"\",\r\n\"password\": \""+xzspj_pwd+"\"\r\n}");
        Request request = new Request.Builder()
                .url(xzspj_token)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        try{
            Response response = client.newCall(request).execute();
            return net.sf.json.JSONObject.fromObject(response.body().string().toString()).getString("token");
        }catch (Exception e){}
        return null;
    }

    public AjaxJson delGXTask(String ids,String reason,String name){
        if(DataUtils.isNotNull(name)){
            if(name.equals("芳草轻松办")){
                HttpRequestUtil.delGXTask(ids,reason, UserUtils.getUser().getLoginName(),fczwdelUrl);
            }else if(name.equals("智慧肖+")){
                HttpRequestUtil.delGXTask(ids,reason, UserUtils.getUser().getLoginName(),xjzwdelUrl);
            }else{
                return AjaxJson.error("暂不提供撤销操作！");
            }
            return AjaxJson.success("操作成功！");
        }else {
            return AjaxJson.error("参数错误！");
        }

    }
}